/**创建智能视频流窗口 */
createVideoByIntelligent = function(divId){
    let containerDom = document.getElementById(divId)
    jessibuca = new JessibucaPro({
        container: containerDom,
        videoBuffer: 0.2, // 缓存时长
        videoBufferDelay: 2, // 1000s
        showBandwidth: false, // 显示网速
        isAnnota: true, // !!!    如果有实时标注需求
        isErrorRePlay: true, // !!!!    如果有报错自动重播需求
        // 硬解配置
        useMSE: true,
        operateBtns: {
            fullscreen: true,
            screenshot: true,
            play: true,
            audio: true,
        },
        heartTimeoutReplayUseLastFrameShow: true,
        // 加载超时时间
        loadingTimeout: 20,
        // 加载超时后 重新请求次数
        loadingTimeoutReplayTimes: -1,
        // ws  超时时间
        heartTimeout: 20,
        // 超时后 重新连接次数
        heartTimeoutReplayTimes: -1,
        showPerformance: false, // 显示性能
    })

    jessibuca.on('ptz', (arrow) => {
        // console.log('ptz', arrow)
    })

    jessibuca.on('streamQualityChange', (value) => {
        // console.log('streamQualityChange', value)
    })

    jessibuca.on('timeUpdate', (value) => {
        // console.log('timeUpdate', value);
    })
    return jessibuca
}
play = function(jessibuca,videoUrl) {
    if (videoUrl) {
        jessibuca.play(videoUrl)
    }
}
/**
 * @param src 视频流全地址
 * @param videoName video 标签id
 */
//全局变量用以保存每个视频的权限
let videoMap = {}
createVideoByJSU3M4 = function (src,videoName){
    let uri = src.split("?")[0]
    let auth = src.split("?")[1]
    let urikey = uri.split("/")[4]
    videoMap[urikey] = auth
    let video = videojs(videoName, {
        autoplay: true,
        controls: true,
        loop: true,
        preload: 'auto',
        width: '100%',
        height: '80',
        sources: [{
        src: uri,
        type: 'application/x-mpegURL',
        }],
    });
    return video
}
createVideoByJSFLV = function (src,videoName){
    let videoPlayer = videojs(videoName, {
        autoplay: 'muted',//自动播放
        controls: true,//用户可以与之交互的控件
        loop: true,//视频一结束就重新开始
        muted: false,//默认情况下将使所有音频静音
        aspectRatio: '16:9',//显示比率
        techOrder: ['html5', 'flvjs'],
        flvjs: {
            mediaDataSource: {
                isLive: false,
                cors: true,
                withCredentials: false,
            },
        },
        sources: [{
            src: src,
            type: 'video/x-flv'
        }],
        controls: true,
        preload: "none"
    });
    return videoPlayer
}
/**
 * 普通摄像头启动调用
 */
videoStart = async function(data = {host: '127.0.0.1',id: '2d748d316eee4a09b514c868d3e39e31'}){
    let rest = await new Promise((resolve, reject) => {
        $.ajax({
          type: 'post',
          url: CONFIG.normalVideoUrl+'/vp/out/start_play_v2',
          data: JSON.stringify(data),
          contentType: 'application/json',
          headers: {},
          success: function (data) {
            resolve(data)
          },
          error: function (err) {
            reject(err);
          }
        })
    })
    // console.log("videoStartvideoStartvideoStart",rest)
    return rest
}


/**
 * 全局过滤请求添加权限
 */
videojs.Vhs.xhr.beforeRequest = function(options) {
    let urikey = options.uri.split("/")[4]
    let auth = videoMap[urikey]
    options.uri = `${options.uri}?`+ auth;
    return options;
  };
/**
 * 智能视频流接口调用
 */
znVideoPlay = async function(channelId,divId){
    var secret="HyJi6HUPx85cl0AHfpLqDsfdGPRM4BAu";
    var serviceIdStr = '192'
    var appId = '3'
    //var channelId = '37017966001310040305'
    var timestampStr= getNowDate();
    var stringSignTemp="appId="+appId+"&channelId="+channelId+"&serviceId="+serviceIdStr+"&timestamp="+timestampStr+secret;

    var signString = CryptoJS.SHA256(stringSignTemp).toString().toUpperCase();

    var param = {
        appId : appId,
        serviceId : serviceIdStr,
        channelId : channelId,
        sign : signString,
        timestamp : timestampStr
    }
    let rest = await new Promise((resolve, reject) => {
        $.ajax({
            type: 'post',
            url: 'http://60.208.85.82:81/cockpit/openCenter/startMark',
            data: JSON.stringify(param),
            contentType: 'application/json',
            headers: {},
            success: function (data) {
                resolve(data)
            },
            error: function (err) {
                reject(err);
            }
        })
    })
    let oo = createVideoByIntelligent(divId)
    play(oo,rest.data.ws)
    return rest
}
refreshVideoPlay = async function(channelId){
    var secret="HyJi6HUPx85cl0AHfpLqDsfdGPRM4BAu";
    var serviceIdStr = '192'
    var appId = '3'
    //var channelId = '37017966001310040305'
    var timestampStr= getNowDate();
    var stringSignTemp="appId="+appId+"&channelId="+channelId+"&serviceId="+serviceIdStr+"&timestamp="+timestampStr+secret;

    var signString = CryptoJS.SHA256(stringSignTemp).toString().toUpperCase();

    var param = {
        appId : appId,
        serviceId : serviceIdStr,
        channelId : channelId,
        sign : signString,
        timestamp : timestampStr
    }
    let rest = await new Promise((resolve, reject) => {
        $.ajax({
            type: 'post',
            url: 'http://60.208.85.82:81/cockpit/openCenter/updateMark',
            data: JSON.stringify(param),
            contentType: 'application/json',
            headers: {},
            success: function (data) {
                resolve(data)
            },
            error: function (err) {
                reject(err);
            }
        })
    })
    return rest
}
initJianKongScreen = async function(){
    let rest = await new Promise((resolve, reject) => {
        $.ajax({
            type: 'get',
            url: 'http://60.208.85.82:81/cockpit/jianKongScreen?type=B',
            headers: {},
            success: function (data) {
                resolve(data)
            },
            error: function (err) {
                reject(err);
            }
        })
    })
    return rest
  }
  initXunchaImage = async function(){
    let rest = await new Promise((resolve, reject) => {
        $.ajax({
            type: 'get',
            url: 'http://60.208.85.82:81/cockpit/queryReport',
            headers: {},
            success: function (data) {
                resolve(data)
            },
            error: function (err) {
                reject(err);
            }
        })
    })
    return rest
  }
  initNewXuncha = async function(myPage, myPageSize, CategoryName){
    let rest = await new Promise((resolve, reject) => {
        $.ajax({
            type: 'get',
            url: 'http://60.208.85.82:81/cockpit/queryCurrMonthReportV2?pageNo=' + myPage + '&pageSize=' + myPageSize + '&largeCategoryName=' + CategoryName,
            headers: {},
            success: function (data) {
                resolve(data)
            },
            error: function (err) {
                reject(err);
            }
        })
    })
    return rest
  }
  // 标准时间转换成年月日时分秒（补0）
function getTime(timestamp) {
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    let Y = date.getFullYear()
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
    let D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    let h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours())
    let m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes())
    let s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds())
    return Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
}

